﻿using Nancy;
using Nancy.Extensions;
using Nancy.IO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;

namespace MockJson
{
    public class CoreModule : NancyModule
    {

        public CoreModule() : base()
        {
            Get["/"] = Index;

            Post["/{*}"] = Process;
        }

        private Response Index(dynamic _)
        {
            return Response.AsText($"MockJson Srv is running");
        }


        private Response Process(dynamic _)
        {
            //    /integration/client/Join

            var path = Request.Path;
            var method = Request.Method;

            try
            {
                var api = App.DB.Queryable<Api>().Where(x => x.Url == path && x.Method == method)
                    .First();

                if (api != null)
                {
                    var responses = App.DB.Queryable<ApiResponse>().Where(x => x.ApiId == api.Id && x.Enable == true).ToList();
                    if (responses.Any())
                    {

                        int totalWeight = responses.Sum(r => r.Weight);

                        // 使用 System.Random 类生成一个随机数
                        Random random = new Random();
                        int randomNumber = random.Next(0, totalWeight);

                        // 根据随机数和加权值选择对应的实体
                        ApiResponse selectedResponse = null;
                        int cumulativeWeight = 0;
                        foreach (var response in responses)
                        {
                            cumulativeWeight += response.Weight;
                            if (randomNumber < cumulativeWeight)
                            {
                                selectedResponse = response;
                                break;
                            }
                        }
                        return Response.AsText(selectedResponse.Response,selectedResponse.ContentType);
                    }
                }

                return new Response() { StatusCode = HttpStatusCode.NotFound };
            }
            catch (Exception ex)
            {
                return new Response() { StatusCode = HttpStatusCode.InternalServerError, ReasonPhrase = $"Internal Server Error:{ex.Message}" };
            }
        }
    }
}
